package com.example.networkdemo

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.networkdemo.network.DoNetworkManager
import com.example.networkdemo.network.NetworkListener
import com.example.networkdemo.ui.theme.NetworkDemoTheme

var name: MutableState<String> = mutableStateOf("Dench")

private const val TAG = "MainActivity"

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NetworkDemoTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    Greeting()
                }
            }
        }

        handleNetwork()
    }

    private fun handleNetwork() {
        Log.d(TAG, "handleNetwork: ")
        DoNetworkManager.addNetworkListener(this, object : NetworkListener {
            override fun onNetChanged(state: Int) {
                when (state) {
                    DoNetworkManager.STATE_WIFI -> {
                        name.value = "WIFI"
                    }
                    DoNetworkManager.STATE_MOBILE -> {
                        name.value = "4G"
                    }
                    else -> {
                        name.value = "UNKNOWN"
                    }
                }
            }
        })
    }

}

@Composable
fun Greeting() {
    Text(text = "当前网络状态：${name.value}!")
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    NetworkDemoTheme {
        Greeting()
    }
}